# coding:utf-8
import random
from django import forms
from django.shortcuts import render, HttpResponse
from django.core.validators import RegexValidator
from django.conf import settings
from utils.tencent_sms import send_sms_single
from .models import UserInfo


# Create your views here.
def send_sms(request):
    """
    地址栏url：?tpl=login或者?tpl=register
    :param request:
    :return:
    """
    tpl = request.GET.get('tpl')
    sms_template_id = settings.TENCENT_SMS_TEMPLATE.get(tpl)
    if not sms_template_id:
        return HttpResponse('模板不存在')
    code = random.randint(1000, 9999)
    send_sms_single('13438229772', sms_template_id, [code, ])
    return HttpResponse('成功')


class RegisterModelForm(forms.ModelForm):
    # 重写phone字段
    phone = forms.CharField(label='手机号', validators=[RegexValidator(r'^1[3-9]\d{9}$')])
    password = forms.CharField(label='密码', widget=forms.PasswordInput())
    confirm_password = forms.CharField(label='确认密码', widget=forms.PasswordInput())
    code = forms.CharField(label='验证码', widget=forms.TextInput())

    class Meta:
        model = UserInfo
        fields = '__all__'

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        for name, field in self.fields.items():
            field.widget.attrs['class'] = 'form-control'
            field.widget.attrs['placeholder'] = '请输入%s' % (field.label,)


def register(request):
    form = RegisterModelForm()
    return render(request, 'test/register.html', locals())
